import { doLogin, getUserInfo, getAccountInfo } from '@/api/user'
import { setSessionStorage, removeSessionStorage } from '@/utils/mixin'

const user = {
  state: {
    userInfo: null, // 用户信息数据
    accountInfo: null, // 用户详细信息数据
    userId: null, // 用户信息数据
    addressList: null // 用户地址数据
  },
  mutations: {
    SET_USERINFO_DATA(state, userInfo) {
      state.userInfo = userInfo
    },
    SET_ACCOUNT_DATA(state, data) {
      state.accountInfo = data
    },
    SET_ADDRESSLIST_DATA(state, addressList) {
      state.addressList = addressList
    }
  },
  actions: {
    // 登录
    DoLogin({ commit, state }, parameterData) {
      return new Promise((resolve, reject) => {
        doLogin(parameterData)
          .then(response => {
            setSessionStorage('b_token', response.data.user_token)
            resolve(response)
          })
          .catch(error => {
            reject(error)
          })
      })
    },
    // 获取用户基本信息
    GetUserInfo({ commit, state }, parameterData) {
      return new Promise((resolve, reject) => {
        getUserInfo(parameterData)
          .then(response => {
            commit('SET_USERINFO_DATA', response.data.userInfo)
            resolve()
          })
          .catch(() => {
            removeSessionStorage('b_token')
          })
      })
    },
    // 获取用户详细信息
    GetAccountInfo({ commit, state }, parameterData) {
      return new Promise((resolve, reject) => {
        getAccountInfo(parameterData)
          .then(response => {
            commit('SET_ACCOUNT_DATA', response.data.userInfo)
            resolve()
          })
          .catch(() => {
            removeSessionStorage('b_token')
          })
      })
    },
    // 前端 登出 清除本地token 不访问接口
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        removeSessionStorage('b_token')
        commit('SET_USERINFO_DATA', null)
        commit('SET_ACCOUNT_DATA', null)
        resolve()
      })
    }
  }
}

export default user
